package com.zzjson.serial;

import java.io.*;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2020 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.serial</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2020年02月19日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class JavaSerializer implements ISerializer {

	@Override
	public <T> byte[] serialize(T obj) {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

		try {
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj);
			return byteArrayOutputStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return new byte[0];
	}

	@Override
	public <T> T deserialize(byte[] data, Class<T> clazz) {
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(data));

			try {
				return (T) objectInputStream.readObject();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
